package com.muse.sentinel.demo1;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;

import lombok.extern.slf4j.Slf4j;

/**
 * Sph.entry时，是否被限流/熔断，通过是否抛出异常来判断的。
 *
 * @author: muse
 * @create: 2021-08-19 10:56
 **/
@Slf4j
public class SentinelSphUSimpleDemo {

    public static void main(String[] args) {
        runFlowRules();
        // runDegradeRules();
    }

    /**
     * 限流规则
     */
    public static void runFlowRules() {
        RulesUtils.initFlowRules();
        Entry entry = null;
        int i = 0;
        while (i < RulesUtils.MAX_NUM) {
            try {
                entry = SphU.entry(RulesUtils.FLOW_RULES_RESOURCES); // 指定流控资源名称
                BusinessService.process(); // 业务逻辑
            } catch (BlockException e) {
                log.error("请求被SphU限流——block!");
                /** 限流后，会走这段代码 */
            } finally {
                if (entry != null) {
                    entry.exit();
                }
            }
            i++;
        }
    }

    /**
     * 熔断规则
     */
    public static void runDegradeRules() {
        RulesUtils.initDegradeRule();
        Entry entry = null;
        int i = 0;
        while (i < RulesUtils.MIN_NUM) {
            try {
                entry = SphU.entry(RulesUtils.DEGRADERULES_RULES_RESOURCES); // 指定熔断资源名称
                BusinessService.processError();
            } catch (BlockException e) {
                log.error("请求被SphU熔断——block!");
                /** 限流后，会走这段代码 */
            } catch (Throwable t) {
                log.error("请求被SphU熔断——业务异常处理！");
                Tracer.trace(t);
            } finally {
                if (entry != null) {
                    entry.exit();
                }
            }
            i++;
        }

    }

}
